/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
'use strict'

import axios from 'axios'
import { getCurTenant } from '@/api/tenant'
import { getToken } from '@/api/login'
import { ElMessage } from 'element-plus'
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

const config = {
  baseURL: localStorage.getItem('baseURL') ?? 'http://139.155.92.140:8081',
  timeout: 1000 * 180
  // withCredentials: true
}

const _axios = axios.create(config)

_axios.interceptors.request.use(
  function (config) {
    // 在请求发送之前做某事
    if (getToken()) {
      // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      config.headers['X-Authorization'] = 'bearer ' + getToken()
    }
    if (getCurTenant()) {
      config.headers['currentTenant'] = getCurTenant()
    }
    return config
  },
  function (error) {
    console.log(error) // for debug
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    /**
     * 下面的注释为通过在response里，自定义code来标示请求状态
     * 当code返回如下情况则说明权限有问题，登出并返回到登录页
     * 如想通过xmlhttprequest来状态码标识 逻辑可写在下面error中
     * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
     * code为非200是抛错 可结合自己业务进行修改
     */
    const res = response.status
    if (res !== 200 && res !== 201 && res !== 204) {
      // this.$message({
      //   message: response.message,
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      return Promise.reject('error')
    } else {
      return response
    }
  },
  function (error) {
    console.log(error.response) // for debug
    console.log(error.message)
    ElMessage({
      message: error.message || error.response.message || error.response.data.message,
      type: 'error',
      duration: 5 * 1000
    })
    // Do something with response error
    return Promise.reject(error)
  }
)

export default _axios
